﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using XChipTool;
using SerialPortHelperLib;
using System.IO.Ports;
using XChip_Common;
using XChipTool.Enties;

namespace XChipTool
{
    public partial class XChip_SimpleUpdateIQ : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;
        public parameter_exportManager Pe_dal;
        List<TreeListValue> ahd1080List =  new List<TreeListValue>(); //用来存储文件
        List<TreeListValue> cvbs1080List = new List<TreeListValue>(); //用来存储文件
        List<TreeListValue> cvi1080List = new List<TreeListValue>(); //用来存储文件
        List<TreeListValue> tvi1080List = new List<TreeListValue>(); //用来存储文件
        List<TreeListValue> ahd720List = new List<TreeListValue>(); //用来存储文件
        List<TreeListValue> cvbs720List = new List<TreeListValue>(); //用来存储文件
        List<TreeListValue> cvi720List = new List<TreeListValue>(); //用来存储文件
        List<TreeListValue> tvi720List = new List<TreeListValue>(); //用来存储文件

        public XChip_SimpleUpdateIQ()
        {
            InitializeComponent();
        }

        private void SB_SelectCommonFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.RestoreDirectory = false;
            ofd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            if(ofd.ShowDialog() == DialogResult.OK)
            {
                TE_CommonPath.Text = ofd.FileName;
            }
        }

        private void SB_SelectOneselfFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.RestoreDirectory = false;
            ofd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                TE_OneselfPath.Text = ofd.FileName;
            }
        }

        private void SB_UpDateCommon_Click(object sender, EventArgs e)
        {
           
            if (!sPortTemp.IsOpen)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            SerialSend.isDebug = false;
            StringBuilder sb = new StringBuilder();
            Pe_dal = new parameter_exportManager();
            if (null != Pe_dal)
            {
                WaitBefore.Start("参数导出", "正在加载中", 60);
                //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
                string sceneStr = string.Empty;
                string cutFun = AppHelper.GetAppConfig("CutFun");
                switch (cutFun)
                {
                    case "0":
                        sceneStr += "ALL";
                        break;
                    case "1"://安防 
                        sceneStr += "安防";
                        break;
                    case "2"://车载  
                        sceneStr += "行车";
                        break;
                    default:
                        break;
                }
                if (cutFun != "0")
                    sceneStr += (SerialSend.ReadRegister((0x80500241), sPortTemp) & 0x08) == 0x08 ? "3D" : "2D";
                var tempList = Pe_dal.GetListToExport(sceneStr);
                //var moduleList = SerialSend.ReadRegister((0x8014080b), sPortTemp) == 1?tempList.Select(c => c.Module).Distinct() : tempList.Where(c => c.Module != "3D DNS" && c.Module != "AE_LFC").Select(c => c.Module).Distinct();//[ 7: 0]Psram_Check_Status;
                var moduleList = tempList.Select(c => c.Module).Distinct();
                if (moduleList.Contains(null))
                {
                    WaitBefore.Close();
                    XtraMessageBox.Show("参数导出寄存器表中存在Module为null的寄存器,无法继续", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                #region 白天寄存器
                //var Pe_patch_dal = new parameter_export_patchManager();
                //var patchList = Pe_patch_dal.GetList();
                var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
                foreach (var item in conditionList)
                {
                    if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
                    {
                        foreach (var item2 in tempList.Where(c => c.ConditionAddr == item))
                        {
                            item2.RelationAddr = null;
                        }
                        //patchList.RemoveAll(c => c.ConditionAddr == item);
                    }
                }
                #endregion
                sb.Append("//IQ_Start\n");
                sb.Append("0xfffd,0x80,\n");
                sb.Append("//10.1 IQ_common");
                //if (SerialSend.ReadRegister((0x8014080b), sPortTemp) == 1)//[ 7: 0]Psram_Check_Status;
                //{
                //tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);

                foreach (var items in moduleList)
                {
                    if (items.Contains("avg_size"))
                        sb.Append("\n//10.2 IQ_oneself");
                    sb.Append($"\n//{items}\n");
                    foreach (var item in tempList.Where(c => c.Module == items).OrderBy(c => c.SortNum))
                    {
                        try
                        {
                            sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                            sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                            if (!string.IsNullOrEmpty(item.ReadAddr))
                            {
                                //if (patchList.Count != 0 && patchList.Select(c => c.ReadAddr).Contains(item.ReadAddr))
                                if (!string.IsNullOrEmpty(item.RelationAddr))
                                {
                                    var regVal = SerialSend.ReadRegister((Convert.ToUInt32(item.RelationAddr.Trim(), 16)), sPortTemp);
                                    //bool isbit7 = !string.IsNullOrEmpty(patchList.Where(c => c.ReadAddr == item.ReadAddr).First().Bit) && patchList.Where(c => c.ReadAddr == item.ReadAddr).First().Bit == "&0x7f";
                                    bool isbit7 = !string.IsNullOrEmpty(item.Bit) && item.Bit == "&0x7f";
                                    sb.Append(isbit7 ? $",0x{(regVal & 0x7f).ToString("x2")}," : $",0x{regVal.ToString("x2")},");
                                }
                                else
                                {
                                    sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                                }
                            }
                            sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                            sb.Append("\n");
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            DevExpress.XtraEditors.XtraMessageBox.Show(item.ReadAddr + "_" + ex.Message);
                            throw;
                        }
                    }
                }
                sb.Append("\n//IQ_End\n");
            }
                SerialSend.isDebug = true;
          
            List<string> listStr = new List<string>();
            StreamReader sr = new StreamReader(TE_CommonPath.Text, Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                listStr.Add(line.ToString());
            }
            sr.Close();
            //查找 IQ_start 开始  IQ_End 结束位置
            var startIndex = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("IQ_start", StringComparison.InvariantCultureIgnoreCase) >= 0);
            var endIndex = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("IQ_End", StringComparison.InvariantCultureIgnoreCase) >= 0);
            var countIndex = (endIndex + 1) - (startIndex + 1);
            if (startIndex == -1 || endIndex == -1)
            {
                XtraMessageBox.Show($"无法找到指定更新位置，请先设置", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //清空对应的数据
            listStr.RemoveRange(startIndex + 1, countIndex);
            //替换数据
            listStr[startIndex] = sb.ToString();

            //List<string> listStr = UpdateParameter(TE_CommonPath.Text);

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.RestoreDirectory = false;
            sfd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            sfd.FileName = Path.GetFileNameWithoutExtension(TE_CommonPath.Text) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllLines(sfd.FileName, listStr.ToArray(), Encoding.Default);
                XtraMessageBox.Show("更新完成，文件保存在" + sfd.FileName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }            
        }
        /// <summary>
        /// 更新iq
        /// </summary>
        /// <param name="filepath"></param>
        /// <returns></returns>
        private List<string> UpdateParameterIQ(string filepath) {

            SerialSend.isDebug = false;
            StringBuilder sb = new StringBuilder();
            Pe_dal = new parameter_exportManager();
            if (null != Pe_dal)
            {
                WaitBefore.Start("参数导出", "正在加载中", 60);
                //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
                string sceneStr = string.Empty;
                string cutFun = AppHelper.GetAppConfig("CutFun");
                switch (cutFun)
                {
                    case "0":
                        sceneStr += "ALL";
                        break;
                    case "1"://安防 
                        sceneStr += "安防";
                        break;
                    case "2"://车载  
                        sceneStr += "行车";
                        break;
                    default:
                        break;
                }
                if (cutFun != "0")
                    sceneStr += (SerialSend.ReadRegister((0x80500241), sPortTemp) & 0x08) == 0x08 ? "3D" : "2D";
                var tempList = Pe_dal.GetListToExport(sceneStr);
                //var moduleList = SerialSend.ReadRegister((0x8014080b), sPortTemp) == 1?tempList.Select(c => c.Module).Distinct() : tempList.Where(c => c.Module != "3D DNS" && c.Module != "AE_LFC").Select(c => c.Module).Distinct();//[ 7: 0]Psram_Check_Status;
                var moduleList = tempList.Select(c => c.Module).Distinct();
                if (moduleList.Contains(null))
                {
                    WaitBefore.Close();
                    //XtraMessageBox.Show("参数导出寄存器表中存在Module为null的寄存器,无法继续", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return null;
                }
                #region 白天寄存器
                //var Pe_patch_dal = new parameter_export_patchManager();
                //var patchList = Pe_patch_dal.GetList();
                var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
                foreach (var item in conditionList)
                {
                    if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
                    {
                        foreach (var item2 in tempList.Where(c => c.ConditionAddr == item))
                        {
                            item2.RelationAddr = null;
                        }
                        //patchList.RemoveAll(c => c.ConditionAddr == item);
                    }
                }
                #endregion
                sb.Append("//IQ_Start\n");
                sb.Append("0xfffd,0x80,\n");
                sb.Append("//10.1 IQ_common");
                //if (SerialSend.ReadRegister((0x8014080b), sPortTemp) == 1)//[ 7: 0]Psram_Check_Status;
                //{
                //tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);

                foreach (var items in moduleList)
                {
                    if (items.Contains("avg_size"))
                        sb.Append("\n//10.2 IQ_oneself");
                    sb.Append($"\n//{items}\n");
                    foreach (var item in tempList.Where(c => c.Module == items).OrderBy(c => c.SortNum))
                    {
                        try
                        {
                            sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
                            sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
                            if (!string.IsNullOrEmpty(item.ReadAddr))
                            {
                                //if (patchList.Count != 0 && patchList.Select(c => c.ReadAddr).Contains(item.ReadAddr))
                                if (!string.IsNullOrEmpty(item.RelationAddr))
                                {
                                    var regVal = SerialSend.ReadRegister((Convert.ToUInt32(item.RelationAddr.Trim(), 16)), sPortTemp);
                                    //bool isbit7 = !string.IsNullOrEmpty(patchList.Where(c => c.ReadAddr == item.ReadAddr).First().Bit) && patchList.Where(c => c.ReadAddr == item.ReadAddr).First().Bit == "&0x7f";
                                    bool isbit7 = !string.IsNullOrEmpty(item.Bit) && item.Bit == "&0x7f";
                                    sb.Append(isbit7 ? $",0x{(regVal & 0x7f).ToString("x2")}," : $",0x{regVal.ToString("x2")},");
                                }
                                else
                                {
                                    sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                                }
                            }
                            sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
                            sb.Append("\n");
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            DevExpress.XtraEditors.XtraMessageBox.Show(item.ReadAddr + "_" + ex.Message);
                            throw;
                        }
                    }
                }
                sb.Append("\n//IQ_End\n");
            }
            SerialSend.isDebug = true;

            List<string> listStr = new List<string>();
            StreamReader sr = new StreamReader(filepath, Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                listStr.Add(line.ToString());
            }
            sr.Close();
            //查找 IQ_start 开始  IQ_End 结束位置
            var startIndex = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("IQ_start", StringComparison.InvariantCultureIgnoreCase) >= 0);
            var endIndex = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("IQ_End", StringComparison.InvariantCultureIgnoreCase) >= 0);
            var countIndex = (endIndex + 1) - (startIndex + 1);
            if (startIndex == -1 || endIndex == -1)
            {
                //XtraMessageBox.Show($"无法找到指定更新位置，请先设置", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            //清空对应的数据
            listStr.RemoveRange(startIndex + 1, countIndex);
            //替换数据
            listStr[startIndex] = sb.ToString();

            return listStr;
        }
        private void SB_UpDateOneself_Click(object sender, EventArgs e)
        {

            List<string> listStr = UpdateParameter(TE_OneselfPath.Text);

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.RestoreDirectory = false;
            sfd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
            sfd.FileName = Path.GetFileNameWithoutExtension(TE_OneselfPath.Text) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllLines(sfd.FileName, listStr.ToArray(), Encoding.Default);
                XtraMessageBox.Show("更新完成，文件保存在" + sfd.FileName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
        /// <summary>
        /// 传入setting路径，更新参数
        /// </summary>
        /// <returns></returns>
        private List<string> UpdateParameter(string filepath)
        {
            StreamReader sr = new StreamReader(filepath, Encoding.Default);
            List<string> listStr = new List<string>();
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                listStr.Add(line);
            }
            sr.Close();
            //全局变量 0xfffd  0xfffe
            string add = "80";//  0xfffd
            string addval = string.Empty; //0xfffe
            string duVal = string.Empty; //读取的值
            //onself iq 也采用这种方式进行更新
            //var startIndex = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("IQ_start", StringComparison.InvariantCultureIgnoreCase) >= 0);
            //var endIndex = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("IQ_End", StringComparison.InvariantCultureIgnoreCase) >= 0);
            var step2Start = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("Step 2 reconfig system", StringComparison.InvariantCultureIgnoreCase) >= 0);
            #region 判断setp2的起始索引
            if (step2Start < 0)
            {
                step2Start = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("Step 2", StringComparison.InvariantCultureIgnoreCase) >= 0);
                if (step2Start < 0)
                {
                    step2Start = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("Step2", StringComparison.InvariantCultureIgnoreCase) >= 0);
                }
            }
            #endregion
            #region 判断sensor的起始索引
            var sensorStart = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("0xfff8", StringComparison.InvariantCultureIgnoreCase) >= 0);
            var sensorEnd = -1;
            if (sensorStart != -1)
            {
                sensorEnd = Array.FindIndex(listStr.ToArray(), sensorStart + 1, t => t.IndexOf("0xfff8", StringComparison.InvariantCultureIgnoreCase) >= 0) + 1;
            }
            else
            {
                sensorStart = Array.FindIndex(listStr.ToArray(), t => t.IndexOf("0xfff0", StringComparison.InvariantCultureIgnoreCase) >= 0);
                if (sensorStart != -1)
                {
                    sensorEnd = Array.FindIndex(listStr.ToArray(), sensorStart + 1, t => t.IndexOf("0xfff0", StringComparison.InvariantCultureIgnoreCase) >= 0) + 1;
                }
            }
            #endregion
            int patchStart = listStr.FindIndex(c => c.ToLower().Contains("patch_start"));
            int patchEnd = listStr.FindIndex(c => c.ToLower().Contains("patch_end"));
            int disableUpdateStart = listStr.FindIndex(c => c.ToLower().Contains("disable_update_start"));
            int disableUpdateEnd = listStr.FindIndex(c => c.ToLower().Contains("disable_update_end"));
            WaitBefore.Start("参数导出", "正在加载中", 60);
            SerialSend.isDebug = false;
            #region 更新逻辑
            for (int i = (step2Start < 0 ? 0 : step2Start); i < listStr.Count(); i++)
            {
                //if ((i >= startIndex && i <= endIndex) || (i >= sensorStart && i <= sensorEnd))
                if (listStr[i].ToLower().Contains("disable_update_start"))
                {
                    while (!listStr[i++].ToLower().Contains("disable_update_end"))
                    {
                        string[] col_re = listStr[i].Replace('，', ',').Split(',');
                        if (col_re.Count() > 2)
                        {
                            string colFirst = col_re.First().Trim().ToLower();
                            //过滤关键字
                            if (colFirst == "0xffff" || colFirst == "0xfff3" || colFirst == "0xfff6" || colFirst == "0xfff7" || colFirst == "0xfff8" || colFirst == "0xfff9" || colFirst == "0xfffa" || colFirst == "0xfff0" || colFirst == "0xfff1")
                            {
                                continue;
                            }
                            else if (colFirst == "0xfffd")
                            {
                                add = col_re[1].Replace("0x", "");
                            }
                            else if (colFirst == "0xfffe")
                            {
                                addval = col_re[1].Replace("0x", "");
                            }
                        }
                    };
                }
                if ((i >= sensorStart && i <= sensorEnd) || (i >= patchStart && i <= patchEnd))//跳过sensor部分和patch部分
                {
                    continue;
                }
                string[] col = listStr[i].Replace('，', ',').Split(',');
                if (col.Count() > 2)
                {
                    string colFirst = col.First().Trim().ToLower();
                    //过滤关键字
                    if (colFirst == "0xffff" || colFirst == "0xfff3" || colFirst == "0xfff6" || colFirst == "0xfff7" || colFirst == "0xfff8" || colFirst == "0xfff9" || colFirst == "0xfffa" || colFirst == "0xfff0" || colFirst == "0xfff1")
                    {
                        continue;
                    }
                    else if (colFirst == "0xfffd")
                    {
                        add = col[1].Replace("0x", "");
                    }
                    else if (colFirst == "0xfffe")
                    {
                        addval = col[1].Replace("0x", "");
                    }
                    else if (colFirst.Contains("0x") && !colFirst.Contains("//"))
                    {
                        try
                        {
                            string sonVal = colFirst.Replace("0x", "").Replace(" ", "");
                            duVal = (add + addval + sonVal.PadLeft(4, '0')).Replace("0x", "").Replace(" ", "").ToLower();
                            if (duVal.Length != 8 || duVal == "80300000" || duVal == "80300001" || duVal == "80300002" || duVal == "80300003" || duVal == "80300004"
                                 || duVal == "8014062c")
                                continue;

                            var tempVal = SerialSend.ReadRegister(Convert.ToUInt32(duVal, 16), sPortTemp);
                            switch (duVal)
                            {
                                case "80500021":
                                    tempVal |= 0x08;
                                    break;
                                case "8050001c":
                                    tempVal |= 0x01;
                                    break;
                                case "80200002":
                                    tempVal &= 0x7f;
                                    break;
                                case "8020002c":
                                    tempVal |= 0x01;
                                    break;
                                case "80500200":
                                    tempVal &= 0x0f;
                                    break;
                                default:
                                    break;
                            }
                            //col[1] = col[1].Contains(" ") ? " 0x" + tempVal.ToString("x2") : "0x" + tempVal.ToString("x2");
                            string oldVal = col[1].Replace("0x", "").Replace(" ", "");
                            col[1] = col[1].Replace(oldVal, tempVal.ToString("x2"));
                            listStr[i] = string.Join(",", col);
                        }
                        catch (Exception ex)
                        {
                            WaitBefore.Close();
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            throw;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    continue;
                }
            }
            #endregion
            SerialSend.isDebug = true;
            WaitBefore.Close();
            return listStr;
        }
        /// <summary>
        /// 加载文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton33_Click(object sender, EventArgs e)
        {
            navigationPane1.SelectedPage = navigationPage1;
            navigationPane1.SelectedPage = navigationPage2;
            navigationPane1.SelectedPage = navigationPage1;
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            //dialog.SelectedPath = AppHelper.GetAppConfig("Folder_Road_Force");
            ///Folder_Road_Force
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                //清空下拉框数据源
                ClearLookUpEditDataSource();
                string foldPath = dialog.SelectedPath;
                //AppHelper.UpdateAppConfig("Folder_Road_Force", foldPath);
                ///*t*/extBox2.Text = foldPath;
                var filePaths = Directory.GetFiles(foldPath, "*.txt").Concat(Directory.GetFiles(foldPath, "*.c")).ToArray();

               var  tlvList = new List<TreeListValue>();
                foreach (var item in filePaths)
                {
                    tlvList.Add(new TreeListValue { ValueMember = Path.GetFileName(item), DisplayMember = item });
                }
                //显示xchip_IQ_common_setting
                IQ_com_txt.Text = tlvList.First(c => c.ValueMember.Contains("IQ_common")).DisplayMember;
                //显示到文件下拉框  //AHD1080   CVBS960   CHD1080  THD1080

                ahd1080List = tlvList.Where(c => c.ValueMember.Contains("AHD1080")).ToList();
                settingPathtxt1.Properties.DataSource = ahd1080List; 
                settingPathtxt2.Properties.DataSource = ahd1080List;
                settingPathtxt1.ItemIndex = 0;
                if (ahd1080List.Count>=2) settingPathtxt2.ItemIndex = 1;
                
                cvbs1080List = tlvList.Where(c => c.ValueMember.Contains("CVBS960")).ToList();
                settingPathtxt3.Properties.DataSource = cvbs1080List;
                settingPathtxt4.Properties.DataSource = cvbs1080List;
                settingPathtxt3.ItemIndex = 0;
                if (cvbs1080List.Count >= 2) settingPathtxt4.ItemIndex = 1;
               
                cvi1080List = tlvList.Where(c => c.ValueMember.Contains("CHD1080")).ToList();
                settingPathtxt5.Properties.DataSource = cvi1080List;
                settingPathtxt6.Properties.DataSource = cvi1080List;
                settingPathtxt5.ItemIndex = 0;
                if (cvi1080List.Count >= 2) settingPathtxt6.ItemIndex = 1;
                tvi1080List = tlvList.Where(c => c.ValueMember.Contains("THD1080")).ToList();
                settingPathtxt7.Properties.DataSource = tvi1080List;
                settingPathtxt8.Properties.DataSource = tvi1080List;
                settingPathtxt7.ItemIndex = 0;
                if (tvi1080List.Count >= 2) settingPathtxt8.ItemIndex = 1;
                //AHD720   CVBS720   CHD720  THD720
                ahd720List = tlvList.Where(c => c.ValueMember.Contains("AHD720")).ToList();
                settingPathtxt9.Properties.DataSource = ahd720List;
                settingPathtxt10.Properties.DataSource = ahd720List;
                settingPathtxt9.ItemIndex = 0;
                if (ahd720List.Count >= 2) settingPathtxt10.ItemIndex = 1;
                cvbs720List = tlvList.Where(c => c.ValueMember.Contains("CVBS720")).ToList();
                settingPathtxt11.Properties.DataSource = cvbs720List;
                settingPathtxt12.Properties.DataSource = cvbs720List;
                settingPathtxt11.ItemIndex = 0;
                if (cvbs720List.Count >= 2) settingPathtxt12.ItemIndex = 1;
                cvi720List = tlvList.Where(c => c.ValueMember.Contains("CHD720")).ToList();
                settingPathtxt13.Properties.DataSource = cvi720List;
                settingPathtxt14.Properties.DataSource = cvi720List;
                settingPathtxt13.ItemIndex = 0;
                if (cvi720List.Count >= 2) settingPathtxt14.ItemIndex = 1;
                tvi720List = tlvList.Where(c => c.ValueMember.Contains("THD720")).ToList();
                settingPathtxt15.Properties.DataSource = tvi720List;
                settingPathtxt16.Properties.DataSource = tvi720List;
                settingPathtxt15.ItemIndex = 0;
                if (tvi720List.Count >= 2) settingPathtxt16.ItemIndex = 1;

                //settingPathtxt1.Properties
            }
        }
        private void ClearLookUpEditDataSource()
        {
            //commonTxt.Properties.DataSource = null; commonTxt.EditValue = string.Empty;
            settingPathtxt1.Properties.DataSource = null; settingPathtxt1.EditValue = string.Empty;
            settingPathtxt2.Properties.DataSource = null; settingPathtxt2.EditValue = string.Empty;
            settingPathtxt3.Properties.DataSource = null; settingPathtxt3.EditValue = string.Empty;
            settingPathtxt4.Properties.DataSource = null; settingPathtxt4.EditValue = string.Empty;
            settingPathtxt5.Properties.DataSource = null; settingPathtxt5.EditValue = string.Empty;
            settingPathtxt6.Properties.DataSource = null; settingPathtxt6.EditValue = string.Empty;
            settingPathtxt7.Properties.DataSource = null; settingPathtxt7.EditValue = string.Empty;
            settingPathtxt8.Properties.DataSource = null; settingPathtxt8.EditValue = string.Empty;
            settingPathtxt9.Properties.DataSource = null; settingPathtxt9.EditValue = string.Empty;
            settingPathtxt10.Properties.DataSource = null; settingPathtxt10.EditValue = string.Empty;
            settingPathtxt11.Properties.DataSource = null; settingPathtxt11.EditValue = string.Empty;
            settingPathtxt12.Properties.DataSource = null; settingPathtxt12.EditValue = string.Empty;
            settingPathtxt13.Properties.DataSource = null; settingPathtxt13.EditValue = string.Empty;
            settingPathtxt14.Properties.DataSource = null; settingPathtxt14.EditValue = string.Empty;
            settingPathtxt15.Properties.DataSource = null; settingPathtxt15.EditValue = string.Empty;
            settingPathtxt16.Properties.DataSource = null; settingPathtxt16.EditValue = string.Empty;
        }
        /// <summary>
        /// 720更新IQ
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void iqbtn9_Click(object sender, EventArgs e)
        {
            var btn = sender as DevExpress.XtraEditors.SimpleButton;
            string path = string.Empty;
            switch (btn.Tag.ToString())
            {
                case "1":
                    if (settingPathtxt9.EditValue == null || settingPathtxt9.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt9.EditValue.ToString();
                    }
                    break;
                case "2":
                    if (settingPathtxt10.EditValue == null || settingPathtxt10.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt10.EditValue.ToString();
                    }
                    break;
                case "3":
                    if (settingPathtxt11.EditValue == null || settingPathtxt11.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt11.EditValue.ToString();
                    }
                    break;
                case "4":
                    if (settingPathtxt12.EditValue == null || settingPathtxt12.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt12.EditValue.ToString();
                    }
                    break;
                case "5":
                    if (settingPathtxt13.EditValue == null || settingPathtxt13.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt13.EditValue.ToString();
                    }
                    break;
                case "6":
                    if (settingPathtxt14.EditValue == null || settingPathtxt14.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt14.EditValue.ToString();
                    }
                    break;
                case "7":
                    if (settingPathtxt15.EditValue == null || settingPathtxt15.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt15.EditValue.ToString();
                    }
                    break;
                case "8":
                    if (settingPathtxt16.EditValue == null || settingPathtxt16.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt16.EditValue.ToString();
                    }
                    break;
                default:
                    break;
            }

            if (!string.IsNullOrEmpty(path))
            {
                List<string> listStr = UpdateParameter(path);
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.RestoreDirectory = false;
                sfd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
                sfd.FileName = Path.GetFileNameWithoutExtension(TE_OneselfPath.Text) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllLines(sfd.FileName, listStr.ToArray(), Encoding.Default);
                    XtraMessageBox.Show("更新完成，文件保存在" + sfd.FileName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }
        /// <summary>
        /// 720更新OS
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void osbtn9_Click(object sender, EventArgs e)
        {
            var btn = sender as DevExpress.XtraEditors.SimpleButton;
            string path = string.Empty;
            switch (btn.Tag.ToString())
            {
                case "1":
                    if (settingPathtxt9.EditValue == null || settingPathtxt9.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt9.EditValue.ToString();
                    }
                    break;
                case "2":
                    if (settingPathtxt10.EditValue == null || settingPathtxt10.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt10.EditValue.ToString();
                    }
                    break;
                case "3":
                    if (settingPathtxt11.EditValue == null || settingPathtxt11.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt11.EditValue.ToString();
                    }
                    break;
                case "4":
                    if (settingPathtxt12.EditValue == null || settingPathtxt12.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt12.EditValue.ToString();
                    }
                    break;
                case "5":
                    if (settingPathtxt13.EditValue == null || settingPathtxt13.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt13.EditValue.ToString();
                    }
                    break;
                case "6":
                    if (settingPathtxt14.EditValue == null || settingPathtxt14.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt14.EditValue.ToString();
                    }
                    break;
                case "7":
                    if (settingPathtxt15.EditValue == null || settingPathtxt15.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt15.EditValue.ToString();
                    }
                    break;
                case "8":
                    if (settingPathtxt16.EditValue == null || settingPathtxt16.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt16.EditValue.ToString();
                    }
                    break;
                default:
                    break;
            }

            if (!string.IsNullOrEmpty(path))
            {
                List<string> listStr = UpdateParameterIQ(path);
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.RestoreDirectory = false;
                sfd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
                sfd.FileName = Path.GetFileNameWithoutExtension(path) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllLines(sfd.FileName, listStr.ToArray(), Encoding.Default);
                    XtraMessageBox.Show("更新完成，文件保存在" + sfd.FileName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }
        /// <summary>
        /// 1080IQ更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void iqbtn1_Click(object sender, EventArgs e)
        {
            var btn = sender as DevExpress.XtraEditors.SimpleButton;
            string path = string.Empty;
            switch (btn.Tag.ToString())
            {
                case "1":
                    if (settingPathtxt1.EditValue == null || settingPathtxt1.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt1.EditValue.ToString();
                    }
                    break;
                case "2":
                    if (settingPathtxt2.EditValue == null || settingPathtxt2.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt2.EditValue.ToString();
                    }
                    break;
                case "3":
                    if (settingPathtxt3.EditValue == null || settingPathtxt3.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt3.EditValue.ToString();
                    }
                    break;
                case "4":
                    if (settingPathtxt4.EditValue == null || settingPathtxt4.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt4.EditValue.ToString();
                    }
                    break;
                case "5":
                    if (settingPathtxt5.EditValue == null || settingPathtxt5.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt5.EditValue.ToString();
                    }
                    break;
                case "6":
                    if (settingPathtxt6.EditValue == null || settingPathtxt6.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt6.EditValue.ToString();
                    }
                    break;
                case "7":
                    if (settingPathtxt7.EditValue == null || settingPathtxt7.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt7.EditValue.ToString();
                    }
                    break;
                case "8":
                    if (settingPathtxt8.EditValue == null || settingPathtxt8.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt8.EditValue.ToString();
                    }
                    break;
                default:
                    break;
            }

            if (!string.IsNullOrEmpty(path))
            {
                List<string> listStr = UpdateParameterIQ(path);
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.RestoreDirectory = false;
                sfd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
                sfd.FileName = Path.GetFileNameWithoutExtension(path) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllLines(sfd.FileName, listStr.ToArray(), Encoding.Default);
                    XtraMessageBox.Show("更新完成，文件保存在" + sfd.FileName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }
        /// <summary>
        /// 1080 OS 更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void osbtn1_Click(object sender, EventArgs e)
        {
            var btn  = sender as DevExpress.XtraEditors.SimpleButton;
            string path = string.Empty;
            switch (btn.Tag.ToString())
            {
                case "1":
                    if (settingPathtxt1.EditValue == null || settingPathtxt1.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else {
                        path = settingPathtxt1.EditValue.ToString();
                    }
                    break;
                case "2":
                    if (settingPathtxt2.EditValue == null || settingPathtxt2.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt2.EditValue.ToString();
                    }
                    break;
                case "3":
                    if (settingPathtxt3.EditValue == null || settingPathtxt3.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt3.EditValue.ToString();
                    }
                    break;
                case "4":
                    if (settingPathtxt4.EditValue == null || settingPathtxt4.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt4.EditValue.ToString();
                    }
                    break;
                case "5":
                    if (settingPathtxt5.EditValue == null || settingPathtxt5.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt5.EditValue.ToString();
                    }
                    break;
                case "6":
                    if (settingPathtxt6.EditValue == null || settingPathtxt6.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt6.EditValue.ToString();
                    }
                    break;
                case "7":
                    if (settingPathtxt7.EditValue == null || settingPathtxt7.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt7.EditValue.ToString();
                    }
                    break;
                case "8":
                    if (settingPathtxt8.EditValue == null || settingPathtxt8.Text.Contains("请"))
                    {
                        path = string.Empty;
                    }
                    else
                    {
                        path = settingPathtxt8.EditValue.ToString();
                    }
                    break;
                default:
                    break;
            }

            if (!string.IsNullOrEmpty(path))
            {
                List<string> listStr = UpdateParameter(path);
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.RestoreDirectory = false;
                sfd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
                sfd.FileName = Path.GetFileNameWithoutExtension(TE_OneselfPath.Text) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllLines(sfd.FileName, listStr.ToArray(), Encoding.Default);
                    XtraMessageBox.Show("更新完成，文件保存在" + sfd.FileName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
           
        }
        /// <summary>
        /// IQ com 的更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void IQComBtn_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(IQ_com_txt.Text))
            {
                List<string> listStr = UpdateParameterIQ(IQ_com_txt.Text);
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.RestoreDirectory = false;
                sfd.Filter = "TXT Files(*.txt;*.c)|*.txt;*.c|All Files(*.*)|*.*";
                sfd.FileName = Path.GetFileNameWithoutExtension(TE_OneselfPath.Text) + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllLines(sfd.FileName, listStr.ToArray(), Encoding.Default);
                    XtraMessageBox.Show("更新完成，文件保存在" + sfd.FileName, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }
    }
}

